/**
 * ZhiZun.com Inc.
 * Copyright (c) 2004-2010 All Rights Reserved.
 */
package com.zhz.lib.cms.utils.zhz;

import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.hibernate.BaseDAO;
import com.zhz.project.common.util.zhzutil.ZhzStringUtil;

/**
 * 页面处理的工具类
 * 
 * @author liwei2672
 * @version $Id: HttpRequestUtil.java, v 0.1 2010-7-17 下午02:38:25 liwei2672 Exp
 *          $
 */
public class ZhzHttpRequestUtil {
    private static Logger logger = Logger.getLogger(ZhzHttpRequestUtil.class);

    /**
     * 从HttpServletRequest提取参数，将参数从ISO转为UTF-8，然后trim <br/>
     * 这个功能也可以通过Filter实现的，但是简单起见，就这样处理了
     * 
     * @param request
     * @param name
     * @return
     */
    public static String getParameters(HttpServletRequest request, String name) {
        return ZhzStringUtil.ISOtoUTF8AfterTrimIfNotNull(request.getParameter(name));
    }

    /**
     *对选择的单个记录进行删除，
     * 
     * @param request
     * @param baseDao
     * @param table
     * @param key
     * @return 是否删除成功
     */
    public static boolean delete(HttpServletRequest request, BaseDAO baseDao, final String table,
                                 final String key) {
        String value = ZhzHttpRequestUtil.getParameters(request, key);
        boolean delResult = false;
        if (ZhzStringUtil.isNotNull(value)) {
            delResult = baseDao.execute("update " + table + "  set ifDelete =1 where " + key + "="
                                        + value);
            if (delResult) {
                request.setAttribute("del", "del");
                request.setAttribute("delResult", "delResult");
            }
        }
        return delResult;
    }

    /**
     *对选择的多个记录进行删除，
     * 
     * @param request
     * @param baseDao
     * @param table
     * @param key
     * @return 是否删除成功
     */
    public static boolean deleteAll(HttpServletRequest request, BaseDAO baseDao,
                                    final String table, final String key) {
        final Set<String> idSet = ZhzHttpRequestUtil.getSelectedIdSet(request);
        Iterator<String> it = idSet.iterator();

        boolean delResult = true;
        int count = idSet.size();
        int errorCount = 0;
        while (it.hasNext()) {

            String value = it.next();

            if (ZhzStringUtil.isNotNull(value)) {

                try {
                    delResult = baseDao.execute("update " + table + "  set ifDelete =1 where "
                                                + key + "=" + value);
                } catch (Exception e) {
                    logger.error("批量删除记录时出现异常，table=" + table + ",key=" + key + ",value=" + value,
                        e);
                    errorCount++;
                    delResult = false;
                }
                request.setAttribute("deleteAll", "deleteAll");
                request.setAttribute("successCount", count-errorCount);
            }
        }

        return delResult;
    }

    /**
     * 基本翻页功能，可以向页面输出连接fanyeHref
     * 
     * @param request
     * @param baseDao
     * @param table
     * @param whereStatement
     * @param order
     * @param pageSize
     * @param LIST
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List getListWithFanyeHref(HttpServletRequest request, BaseDAO baseDao,
                                            final String table, String whereStatement,
                                            final String order, int pageSize, String LIST,
                                            StringBuffer fanyeHref) {

        int entryTatal = baseDao.getNumOnQuery(" from " + table + whereStatement);

        // ///////////////////////////////////////
        // 获取页值
        int pageNow = 0;
        String pageNowString = ZhzHttpRequestUtil.getParameters(request, "pageNow");

        if (ZhzStringUtil.isNotNull(pageNowString)) {
            pageNow = Integer.parseInt(pageNowString.trim());
        } else {
            pageNow = 1;
        }
        if (pageNow <= 1)
            pageNow = 1;

        int pageTatal = 0;
        if (entryTatal / pageSize > 0)
            pageTatal = entryTatal / pageSize + 1;
        else
            pageTatal = entryTatal / pageSize;
        if (pageNow > pageTatal) {
            pageNow = pageTatal;
        }

        // ///////////////////////////////////////
        // 根据当前页等条件查询
        List list = baseDao.findAllByPage(table, whereStatement, order, pageNow, pageSize);

        // 查询的结果集
        request.setAttribute(LIST, list);

        request.setAttribute("pageNow", pageNow);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("pageTatal", pageTatal);
        request.setAttribute("entryTatal", entryTatal);
        request.setAttribute("fanyeHref", fanyeHref.toString());

        return list;
    }

    /**
     * 获取记录
     * 
     * @param request
     * @param baseDao
     * @param TABLE
     * @param KEY
     * @param name
     * @return 查询的对象
     */
    public static Object getRecord(HttpServletRequest request, BaseDAO baseDao, String TABLE,
                                   String KEY, String name) {
        String value = ZhzHttpRequestUtil.getParameters(request, KEY);

        Object object = null;
        if (ZhzStringUtil.isNotNull(value)) {
            object = baseDao.findOneObject(TABLE, KEY, value);
            request.setAttribute(name, object);
        }
        return object;
    }

    /**
     * 将HashMap写进Request里面
     * 
     * @param map
     *            HashMap
     * @param fileName
     *            文件名
     */
    @SuppressWarnings("unchecked")
    public static void writeMapToRequest(HttpServletRequest request, Map map) {
        Set keys = map.entrySet();
        for (Iterator it = keys.iterator(); it.hasNext();) {
            java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
            request.setAttribute((String) (entry.getKey()), entry.getValue());
        }
    }

    /**
     * 将HashMap写进ModelMap里面
     * 
     * @param map
     *            HashMap
     * @param fileName
     *            文件名
     */
    @SuppressWarnings("unchecked")
    public static void writeMapToModelMap(ModelMap model, Map map) {
        Set keys = map.entrySet();
        for (Iterator it = keys.iterator(); it.hasNext();) {
            java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
            model.put((entry.getKey()), entry.getValue());
        }
    }

    /**
     * 提取多选框选中的多个id
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Set<String> getSelectedIdSet(HttpServletRequest request) {
        //获取所有的参数
        Enumeration allParameter = request.getParameterNames();

        //获取选择的所有待审核的模块
        final Set<String> idSet = new HashSet<String>();

        String name = null;
        while (allParameter.hasMoreElements()) {
            name = (String) allParameter.nextElement();
            if (ZhzStringUtil.isNotNull(name) && StringUtil.contains(name, "checkbox")) {
                // 将含有值的checkbox，赋值
                idSet.add(request.getParameter(name));
            }
        }
        return idSet;
    }
}
